package com.ship.dispatch.util;


import com.ship.common.core.domain.R;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.DateUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.dispatch.bean.fob.SpFobFileRecord;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysFile;
import com.ship.system.api.domain.SysUser;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Map;

@Component
public class WordUtil {

//    @Value("${file_server.host}")
//    private String fileServerHost;
//    private static final String FILE_UPLOAD_PATH = "/group1/upload";

    @Autowired
    SpFobFileRecordService fileRecordService;
    //public static String replaceSin(String filePath,List<>)

    @Autowired
    private RemoteFileService remoteFileService;

    public void updateFileTemplate(Long serviceId, String templateId, Map<String, SysUser> map,String bussniessFilee){
        SpFobFileRecord fobFileRecord = null;
        if(StringUtils.isNotEmpty(bussniessFilee)){
            fobFileRecord = fileRecordService.getById(bussniessFilee);
        }
        if(fobFileRecord==null){
            fobFileRecord = fileRecordService.selectByServiceAndTemplate(serviceId,templateId);
        }
        if(fobFileRecord!=null){
            try {
                URL httpUrl = null;
                File file = new File(fobFileRecord.getPath());
                String name = URLDecoder.decode(file.getName(), "UTF-8");
                file.delete();
//               // 读取文件
                String oldPart = "http://10.75.33.149:9300/statics";
                String newPart = "https://lngshipping.cgp.cnooc/api/file/statics";

                String newUrl = fobFileRecord.getPath();
                if (newUrl.contains("https://lngshipping.cgp.cnooc")) {
                    newUrl = newUrl.replace(newPart, oldPart);
                }
                httpUrl = new URL(newUrl);
                InputStream inputStream = httpUrl.openConnection().getInputStream();
//               String encodedFilePath = fobFileRecord.getPath().replace(" ", "%20");
//               URI httpUrl = new URI(encodedFilePath);
//               URL uri = httpUrl.toURL();
//               InputStream inputStream = uri.openConnection().getInputStream();
                XWPFDocument document = new XWPFDocument(inputStream); // 加载Word文档

                for(String key:map.keySet()){
                    boolean flag = true;
                    int i=0;
                    while (flag){
                        XWPFParagraph paragraph = document.getParagraphArray(i); // 获取文档中的第一个段落，可以根据需要选择其他段落
                        if(paragraph==null) {
                            flag = false;
                            break;
                        }
                        String searchText = key; // 需要搜索的文本
                        String imgFile = map.get(key).getSign(); // 需要插入的签名图片文件
                        URL imgUrl = null;
                        InputStream imgStream = null;
                        if(imgFile!=null && StringUtils.isNotEmpty(imgFile)){
                            imgUrl = new URL(imgFile);
                            imgStream = imgUrl.openConnection().getInputStream();
                        }
                        for (XWPFRun run : paragraph.getRuns()) {
                            String text = run.getText(run.getTextPosition());
                            if (text != null && text.contains(searchText)) {
                                if(imgUrl!=null){
                                    // 找到文本位置，插入图片
                                    // 图片尺寸可以根据需要调整
                                    if(imgFile.contains(".png")){
                                        // 找到文本位置，插入图片
                                        run.addPicture(imgStream,
                                                XWPFDocument.PICTURE_TYPE_PNG, imgFile,
                                                Units.toEMU(150), Units.toEMU(20)); // 图片尺寸可以根据需要调整
                                        run.setText(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",map.get(key).getCreateTime()));
                                    }else {
                                        // 找到文本位置，插入图片
                                        run.addPicture(imgStream,
                                                XWPFDocument.PICTURE_TYPE_JPEG, imgFile,
                                                Units.toEMU(150), Units.toEMU(20)); // 图片尺寸可以根据需要调整
                                        run.setText(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",map.get(key).getCreateTime()));
                                    }
                                }else { // 替换文字
                                    run.setText( map.get(key).getNickName()+" "+ DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",map.get(key).getCreateTime()));
                                    //break; // 如果只需要插入一张图片，则可以在这里停止搜索
                                }
                            }
                        }
                        i++;
                    }
                }
                OutputStream outputStream = new FileOutputStream(name);
                document.write(outputStream);
                document.close();
                outputStream.close();
                FileInputStream fileInputStream = new FileInputStream(name);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer2 = new byte[1024];
                int len2;
                while ((len2 = fileInputStream.read(buffer2)) > -1) {
                    out.write(buffer2, 0, len2);
                }
                fileInputStream.close();
                InputStream byteArrayInputStream = new ByteArrayInputStream(out.toByteArray());
                /*File file1 = new File("测试.docx");
                saveToFile(byteArrayInputStream,file1);*/
                String url = upload(byteArrayInputStream,name);
                fobFileRecord.setPath(url);
                if(fobFileRecord.getTemplateId()==null && StringUtils.isNotEmpty(templateId)){
                    fobFileRecord.setTemplateId(Long.parseLong(templateId));
                }
                fobFileRecord.setOrderDetailId(fobFileRecord.getTemplateId());
                fileRecordService.updateById(fobFileRecord);
            } catch (Exception e) {
                throw new BusException("解析文档失败",BaseResultCode.GENERAL_ERROR);
            }
        }
    }

    public void updateFile(Long serviceId, Map<String, SysUser> map){
        SpFobFileRecord fobFileRecord = fileRecordService.getById(serviceId);
        if(fobFileRecord!=null){
            try {
                URL httpUrl = null;
                File file = new File(fobFileRecord.getPath());
                String name = file.getName();
                file.delete();
                // 读取文件
                httpUrl = new URL(fobFileRecord.getPath());
                InputStream inputStream = httpUrl.openConnection().getInputStream();
//                String encodedFilePath = fobFileRecord.getPath().replace(" ", "%20");
//                URI httpUrl = new URI(encodedFilePath);
//                URL uri = httpUrl.toURL();
//                InputStream inputStream = uri.openConnection().getInputStream();
                XWPFDocument document = new XWPFDocument(inputStream); // 加载Word文档

                for(String key:map.keySet()){
                    boolean flag = true;
                    int i=0;
                    while (flag){
                        XWPFParagraph paragraph = document.getParagraphArray(i); // 获取文档中的第一个段落，可以根据需要选择其他段落
                        if(paragraph==null) {
                            flag = false;
                            break;
                        }
                        String searchText = key; // 需要搜索的文本
                        String imgFile = map.get(key).getSign(); // 需要插入的签名图片文件
                        URL imgUrl = null;
                        InputStream imgStream = null;
                        if(imgFile!=null && imgFile!=""){
                            imgUrl = new URL(imgFile);
                            imgStream = imgUrl.openConnection().getInputStream();
                        }
                        for (XWPFRun run : paragraph.getRuns()) {
                            String text = run.getText(run.getTextPosition());
                            if (text != null && text.contains(searchText)) {
                                if(imgUrl!=null){
                                    if(imgFile.contains(".png")){
                                        // 找到文本位置，插入图片
                                        run.addPicture(imgStream,
                                                XWPFDocument.PICTURE_TYPE_PNG, imgFile,
                                                Units.toEMU(150), Units.toEMU(20)); // 图片尺寸可以根据需要调整
                                        run.setText(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",map.get(key).getCreateTime()));

                                    }else {
                                        // 找到文本位置，插入图片
                                        run.addPicture(imgStream,
                                                XWPFDocument.PICTURE_TYPE_JPEG, imgFile,
                                                Units.toEMU(150), Units.toEMU(20)); // 图片尺寸可以根据需要调整
                                        run.setText(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",map.get(key).getCreateTime()));
                                    }
                                }else { // 替换文字
                                    run.setText( map.get(key).getNickName()+" "+ DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",map.get(key).getCreateTime()));
                                    break; // 如果只需要插入一张图片，则可以在这里停止搜索
                                }
                            }
                        }
                        i++;
                    }
                }
                OutputStream outputStream = new FileOutputStream(name);
                document.write(outputStream);
                document.close();
                outputStream.close();
                FileInputStream fileInputStream = new FileInputStream(name);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer2 = new byte[1024];
                int len2;
                while ((len2 = fileInputStream.read(buffer2)) > -1) {
                    out.write(buffer2, 0, len2);
                }
                fileInputStream.close();
                InputStream byteArrayInputStream = new ByteArrayInputStream(out.toByteArray());
               /* File file1 = new File("测试.docx");
                saveToFile(byteArrayInputStream,file1);*/
                String url = upload(byteArrayInputStream,name);
                fobFileRecord.setPath(url);
                fileRecordService.updateById(fobFileRecord);
            } catch (Exception e) {
                throw new BusException("解析文档失败",BaseResultCode.GENERAL_ERROR);
            }
        }
    }
    public static void saveToFile(InputStream inStream, File file) throws IOException {
        if (file.exists()) {
            throw new IOException("File already exists");
        }
        try (OutputStream outStream = new FileOutputStream(file)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }
        }
    }

    /**
     * 上传附件M
     * @return
     */
    public String upload(InputStream inputStream, String name) throws IOException {

        MultipartFile multipartFile = new MockMultipartFile("file", name, "application/octet-stream", inputStream);
        R<SysFile> result1 = remoteFileService.upload(multipartFile);
        if(result1.getCode() != R.SUCCESS){
            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
        }
        String result = result1.getData().getHttpsUrl();
        try{
            File tempFile = new File(multipartFile.getOriginalFilename());
            if(tempFile.exists()){
                tempFile.delete();
            }
        }catch (Exception e){
        }
//        try {
//            InputStreamResource isr = new InputStreamResource(inputStream,
//                    name);
//
//            Map<String, Object> params = new HashMap<>();
//            params.put("file", isr);
//            //params.put("path", "86501729");
//            params.put("output", "json");
//            /*params.put("auth_token", "123");*/
//            String resp = HttpRequest.post(fileServerHost + FILE_UPLOAD_PATH).form(params).timeout(-1).execute().body();
//            //String resp = HttpUtil.post(fileServerHost + FILE_UPLOAD_PATH, params);
//            JSONObject re = JSONObject.parseObject(resp);
//            if(!re.getString("retcode").equals("0")){
//                throw new BusException(re.getString("retmsg"), BaseResultCode.GENERAL_ERROR);
//            }
//            result = re.getString("domain") + re.getString("path");
//        } catch (Exception e) {
//            throw new BusException("文件服务器连接失败",BaseResultCode.GENERAL_ERROR);
//        }
        return result;
    }
}
